import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by liukaixin on 16/5/19.
 */
public class ProductManager {

    private List<Product> productsList = new ArrayList<>();

    private static ProductManager productManager = new ProductManager();

    private ProductManager() {

    }

    public static ProductManager getProductManager() {
        return productManager;
    }

    public Product getProductByBarcode(String barcode) {
        return this.productsList.stream().filter(product -> product.getBarcode().equals(barcode)).findFirst().get();
    }

    public void setProduct(String jsonString) {
        String[] products = JSONDecoder.decodeArrayFrom(jsonString);
        for (String product1 : products) {
            Product product = new Product();
            product.setBarcode(JSONDecoder.decodeStringWithName(product1, "barcode"));
            product.setName(JSONDecoder.decodeStringWithName(product1, "name"));
            product.setUnit(JSONDecoder.decodeStringWithName(product1, "unit"));
            product.setCategory(JSONDecoder.decodeStringWithName(product1, "category"));
            product.setSubCategory(JSONDecoder.decodeStringWithName(product1, "subCategory"));
            product.setPrice(JSONDecoder.decodeDoubleWithName(product1, "price"));
            productsList.add(product);
        }
    }
}
